package com.google.code.irouter.utils;

import com.google.appengine.repackaged.com.google.common.base.StringUtil;
import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.google.appengine.repackaged.com.google.common.util.Base64DecoderException;

public final class TextUtil {

	private static String SEPARATOR;

	static {
		SEPARATOR = PropertyUtil.getProperty("i-router.default.separator");
	}

	public static String encodeBASE64(String string) {
		return Base64.encode(string.getBytes());
	}

	public static String decodeBASE64(String string) {
		try {
			return new String(Base64.decode(string));
		} catch (Base64DecoderException e) {
			return null;
		}
	}

	public static String contact(String... strings) {
		return contact(false, strings);
	}

	public static String contact(boolean hasSeparator, String... strings) {
		StringBuffer stringBuffer = new StringBuffer();
		for (String string : strings) {
			stringBuffer.append(string);
			if (hasSeparator)
				stringBuffer.append(SEPARATOR);
		}
		return StringUtil.trimEnd(stringBuffer.toString(), SEPARATOR);
	}

	public static String cut(String strParameter, int limitLength) {
		limitLength = limitLength - 20;
		limitLength = limitLength * 2;
		String return_str = strParameter;
		int temp_int = 0;
		int cut_int = 0;
		byte[] b = strParameter.getBytes();
		for (int i = 0; i < b.length; i++) {
			if (b[i] >= 0) {
				temp_int = temp_int + 1;
			} else {
				temp_int = temp_int + 2;
				i++;
			}
			cut_int++;

			if (temp_int >= limitLength) {
				if (temp_int % 2 != 0 && b[temp_int - 1] < 0) {
					cut_int--;
				}
				return_str = return_str.substring(0, cut_int);
				break;
			}
		}
		return return_str;
	}

}
